<?php
/**
 * 商家中心抢购管理
 */
defined('IN_KG') or exit('Access Invalid!');

class store_groupbuyControl extends BaseSellerControl
{

    public function __construct()
    {
        parent::__construct();

        //读取语言包
        Language::read('member_groupbuy');
        //检查抢购功能是否开启
        /*if (intval(C('groupbuy_allow')) !== 1) {
            showMessage(Language::get('groupbuy_unavailable'), 'index.php?control=seller_center', '', 'error');
        }*/
    }

    /**
     * 默认显示抢购列表
     **/
    public function indexOp()
    {
        $this->groupbuy_listOp();
    }


    /**
     * 抢购套餐购买
     **/
    public function groupbuy_quota_addOp()
    {
        //输出导航
        self::profile_menu('groupbuy_quota_add');
        Tpl::showpage('store_groupbuy_quota.add');
    }

    /**
     * 抢购套餐购买保存
     **/
    public function groupbuy_quota_add_saveOp()
    {
        $groupbuy_quota_quantity = intval($_POST['groupbuy_quota_quantity']);
        if ($groupbuy_quota_quantity <= 0) {
            showDialog('购买数量不能为空');
        }

        $model_groupbuy_quota = Model('groupbuy_quota');

        //获取当前价格
        $current_price = intval(C('groupbuy_price'));

        //获取该用户已有套餐
        $current_groupbuy_quota = $model_groupbuy_quota->getGroupbuyQuotaCurrent($_SESSION['store_id']);
        $add_time = 86400 * 30 * $groupbuy_quota_quantity;
        if (empty($current_groupbuy_quota)) {
            //生成套餐
            $param = array();
            $param['member_id'] = $_SESSION['member_id'];
            $param['member_name'] = $_SESSION['member_name'];
            $param['store_id'] = $_SESSION['store_id'];
            $param['store_name'] = $_SESSION['store_name'];
            $param['start_time'] = TIMESTAMP;
            $param['end_time'] = TIMESTAMP + $add_time;
            $model_groupbuy_quota->addGroupbuyQuota($param);
        } else {
            $param = array();
            $param['end_time'] = array('exp', 'end_time + ' . $add_time);
            $model_groupbuy_quota->editGroupbuyQuota($param, array('quota_id' => $current_groupbuy_quota['quota_id']));
        }

        //记录店铺费用
        $this->recordStoreCost($current_price * $groupbuy_quota_quantity, '购买抢购');

        $this->recordSellerLog('购买' . $groupbuy_quota_quantity . '份抢购套餐，单价' . $current_price . L('nc_yuan'));

        showDialog(Language::get('groupbuy_quota_add_success'), urlShop('store_groupbuy', 'groupbuy_list'), 'succ');
    }

    /**
     * 抢购列表
     **/
    public function groupbuy_listOp()
    {
        $model_groupbuy = Model('groupbuy');
        $model_groupbuy_quota = Model('groupbuy_quota');

        if (checkPlatformStore()) {
            Tpl::output('isOwnShop', true);
        } else {
            $current_groupbuy_quota = $model_groupbuy_quota->getGroupbuyQuotaCurrent($_SESSION['store_id']);
            Tpl::output('current_groupbuy_quota', $current_groupbuy_quota);
        }

        $condition = array();
        $condition['store_id'] = $_SESSION['store_id'];
        if (!empty($_GET['groupbuy_state'])) {
            $condition['state'] = $_GET['groupbuy_state'];
        }
        $condition['groupbuy_name'] = array('like', '%' . $_GET['groupbuy_name'] . '%');

        if (strlen($groupbuy_vr = trim($_GET['groupbuy_vr']))) {
            $condition['is_vr'] = $groupbuy_vr ? 1 : 0;
            Tpl::output('groupbuy_vr', $groupbuy_vr);
        }
        $groupbuy_list = $model_groupbuy->getGroupbuyExtendList($condition, 10);
        Tpl::output('group', $groupbuy_list);
        Tpl::output('show_page', $model_groupbuy->showpage());
        Tpl::output('groupbuy_state_array', $model_groupbuy->getGroupbuyStateArray());

        self::profile_menu('groupbuy_list');
        Tpl::showpage('store_groupbuy.list');
    }


    /**
     * 添加抢购页面
     **/
    public function groupbuy_addOp()
    {
        $model_groupbuy_quota = Model('groupbuy_quota');

        if (checkPlatformStore()) {
            Tpl::output('isOwnShop', true);
        } else {
            $current_groupbuy_quota = $model_groupbuy_quota->getGroupbuyQuotaCurrent($_SESSION['store_id']);
            if (empty($current_groupbuy_quota)) {
                showMessage('当前没有可用套餐，请先购买套餐', urlShop('store_groupbuy', 'groupbuy_quota_add'), '', 'error');
            }
            Tpl::output('current_groupbuy_quota', $current_groupbuy_quota);
        }

        // 根据后台设置的审核期重新设置抢购开始时间
        Tpl::output('groupbuy_start_time', TIMESTAMP + intval(C('groupbuy_review_day')) * 86400);

        Tpl::output('groupbuy_classes', Model('groupbuy')->getGroupbuyClasses());

        self::profile_menu('groupbuy_add');
        Tpl::showpage('store_groupbuy.add');

    }

    /**
     * 抢购保存
     **/
    public function groupbuy_saveOp()
    {
        $fields = [
            'groupbuy_name'    => '/.+/',
            'groupbuy_remark'  => '/.+/',
            'start_time'       => '/\d{4}-\d{1,2}-\d{1,2}.\d{1,2}\:\d{1,2}/',
            'end_time'         => '/\d{4}-\d{1,2}-\d{1,2}.\d{1,2}\:\d{1,2}/',
            'groupbuy_deposit' => '/\d+/',
            'upper_limit'      => '/\d+/',
            'groupbuy_intro'   => '/.+/',
            'recommended'      => '/\d/',
        ];

        $message = [
            'groupbuy_name'    => '请输入团购名称',
            'groupbuy_remark'  => '请输入团购副标题',
            'start_time'       => '活动开始时间格式错误',
            'end_time'         => '结束时间错误',
            'groupbuy_deposit' => '定金数据错误',
            'upper_limit'      => '团购总数错误',
            'groupbuy_intro'   => '请输入活动介绍',
            'recommended'      => '推荐选项错误',
        ];

        foreach ($fields as $field => $rule) {
            if (!preg_match($rule, $_POST[$field])) {
                showDialog($item . '错误', 'index.php?control=store_groupbuy');
                die;
            }
        }

        $goods = $_POST['goods'];
        foreach ($goods as $persons => $priceCombo) {
            $goodCombo[$persons] = array();
            foreach ($priceCombo as $item => $value) {
                if (!isset($goods_id)) {
                    $goods_id = $item;
                }
                $data[] = [
                    'g_id'    => $item,
                    'g_price' => $value
                ];
            }
            $goodCombo[$persons] = $data;
            unset($data);
        }

        $goods_info = Model('goods')->where(array('goods_id' => $goods_id))->find();
        $insert = [
            'groupbuy_name'    => $_POST['groupbuy_name'],
            'start_time'       => strtotime($_POST['start_time']),
            'end_time'         => strtotime($_POST['end_time']),
            'goods_commonid'   => $goods_info['goods_commonid'],
            'goods_name'       => $goods_info['goods_name'],
            'store_id'         => $goods_info['store_id'],
            'store_name'       => $goods_info['store_name'],
            'goods_price'      => $goods_info['goods_price'],
            'groupbuy_info'    => serialize($goodCombo),
            'groupbuy_deposit' => $_POST['groupbuy_deposit'],  //定金
            'groupbuy_price'   => $goods_info['goods_price'],
            'virtual_quantity' => rand(10, 200),
            'upper_limit'      => $_POST['upper_limit'],
            'groupbuy_intro'   => urlencode($_POST['groupbuy_intro']),
            'state'            => 20,
            'recommended'      => $_POST['recommended'] ? 1 : 0,
            'class_id'         => 0,
            'groupbuy_image'   => $goods_info['goods_image'],
            'is_vr'            => 0,
        ];
        $groupbuy = Model('groupbuy');
        $groupbuy->insert($insert);
        showDialog(Language::get('groupbuy_add_success: ' . $status), 'index.php?control=store_groupbuy', 'succ', '', 3);
    }


    /*更改团购参与人数*/
    public function groupbuy_add_buyer_countOp()
    {
        $number = $_POST['number'];
        $groupbuy_id = $_POST['groupbuy_id'];
        if (!preg_match('/\d+/', $number) && !preg_match('/^[1-9]{1,5}$/', $groupbuy_id)) {
            $this->_return_err(400, '参数错误');
        }
        //where(array('link_id'=>2))->setInc('link_sort',3)
        Model('groupbuy')->where(array('groupbuy_id' => $groupbuy_id))->setInc('buyer_count', $number);
        $this->_return_err(200, '更改成功');
    }

    /*团购活动推荐*/
    public function groupbuy_recommonOp()
    {
        $statsu = intval($_POST['recommon_status']);
        $groupbuy_id = $_POST['groupbuy_id'];

        if (!in_array($statsu, array(0, 1))) {
            $this->_return_err(400, '活动状态信息错误');
        }
        if (!preg_match('/^[1-9]\d+$/', $groupbuy_id)) {
            $this->_return_err(400, '团购活动id错误');
        }

        Model('groupbuy')->where(array('groupbuy_id' => $groupbuy_id))->update(['recommended' => $statsu]);
        $this->_return_err(200, '更改成功');
    }

    /*团购订单*/
    public function gruopbuy_infoOp()
    {
        $groupbuy_id = intval($_GET['group_id']);
        $groupbuyOrders = Model('groupbuy_orders')->where(array('groupbuy_id' => $groupbuy_id))->select();

        $deposit_order_id = array_column($groupbuyOrders, 'deposit_order_id');

        $condition['order_id'] = array('in', implode(',', $deposit_order_id));
        $deposit_order_list = Model('orders')->where($condition)->select();

        $deposit_order_goods = Model('order_goods')->where($condition)->select();
        foreach ($deposit_order_goods as $good_key => $good_value){
            foreach ($deposit_order_list as $order_key => $order_value){
                if ($deposit_order_goods[$good_key]['order_id'] == $deposit_order_list[$order_key]['order_id']){
                    $deposit_order_list[$order_key]['goods_info'] = $deposit_order_goods[$good_key];
                    break;
                }
            }
        }

        Tpl::output('order', $deposit_order_list);

        self::profile_menu('groupbuy_list');
        Tpl::showpage('store_groupbuy_deposit.list');
    }

    /*取消订单,退订金*/
    public function gruopbuy_order_cancelOp()
    {
        $order_id = $_POST['order_id'];
        if (!preg_match('/^[1-9](\d+)?$/', $order_id)) {
            $this->_return_err(400, '订单ID错误');
        }

        $model_refund = Model('refund_return');
        $model_order = Model('order');
        $logic_order = Logic('order');
        //$member_id = $this->member_info['member_id'];

        $model_trade = Model('trade');
        $order_paid = $model_trade->getOrderState('order_paid');//订单状态20:已付款

        $condition = array();
        //$condition['buyer_id'] = $member_id;
        $condition['order_id'] = $order_id;
        $condition['order_state'] = $order_paid;
        $order_info = $model_order->getOrderInfo($condition);;
        $payment_code = $order_info['payment_code'];//支付方式

        $condition = array();
        $condition['buyer_id'] = $order_info['buyer_id'];
        $condition['order_id'] = $order_id;
        $condition['goods_id'] = '0';
        $condition['seller_state'] = array('lt', '3');
        /**
         * v2.01新增字段，判断该退款退货是否关闭。用于重新退货。
         */
        $condition['delete_state'] = 1;
        $refund = $model_refund->getRefundReturnInfo($condition);
        // print_r($condition);die();
        if (empty($order_info) || $payment_code == 'offline' || $refund['refund_id'] > 0 ) {
            $this->_return_err(400, '取消失败');
        } else {
            $book_amount = Logic('order_book')->getDepositAmount($order_info);//订金金额
            $allow_refund_amount = ncPriceFormat($order_info['order_amount'] - $book_amount);//可退款金额

            $refund_array = array();
            $refund_array['refund_type'] = '1';//类型:1为退款,2为退货
            $refund_array['seller_state'] = '2';//状态:1为待审核,2为同意,3为不同意
            $refund_array['order_lock'] = '2';//锁定类型:1为不用锁定,2为需要锁定
            $refund_array['refund_state'] = '2';
            $refund_array['goods_id'] = '0';
            $refund_array['order_goods_id'] = '0';
            $refund_array['reason_id'] = '0';
            $refund_array['reason_info'] = '取消订单，全部退款';
            $refund_array['goods_name'] = '订单商品全部退款';
            $refund_array['refund_amount'] = ncPriceFormat($allow_refund_amount);
            if ($order_info['order_type'] == 4) {
                $message = '团购押金退款,订单号：' . $order_info['order_sn'];

                //将尾款订单取消
                $groupbuy_order = Model('groupbuy_orders')->where(array('deposit_order_id' => $order_id))->find();
                if ($groupbuy_order['paid_order_id'] > 0){
                    $cancal['order_state'] = 0;
                    $cancal['delete_state'] = 1;
                    $status =  $model_order->where(array('order_id' => $groupbuy_order['paid_order_id']))->update($cancal);
                }

            } elseif ($order_info['order_type'] == 5) {
                $message = '团购尾款退款' . $order_info['order_sn'];
            }
            $refund_array['buyer_message'] = $message;
            $refund_array['add_time'] = time();

            $pic_array = array();
            $pic_array['buyer'] = $_POST['refund_pic'];//上传凭证
            $info = serialize($pic_array);
            $refund_array['pic_info'] = $info;
            $refund_id = $model_refund->addRefundReturn($refund_array, $order_info);

            Model('cron')->delCron(array('order_id' => $order_id));
            //$user = isset($user) ? $user : $this->member_info['member_name'];
            $result = $logic_order->changeOrderStateCancel($order_info, 'buyer', '', '');
            // 取消订单后，更新统计表信息

            Logic('stat')->updateOrderStat(array(array('order_id' => $order_id)));

            if (!$result['state']) {
                $this->_return_err(400, $result['msg']);
            } else {
                $this->_return_err(200, '取消订单成功,请及时完成订金退款');
            }
        }
    }


    private function _return_err($code, $msg)
    {
        echo json_encode([
            'code' => $code,
            'msg'  => $msg
        ]);
        die;
    }


    public function groupbuy_goods_infoOp()
    {

        $goods_commonid = intval($_GET['goods_commonid']);

        $data = array();
        $data['result'] = true;

        $model_goods = Model('goods');

        $condition = array();
        $condition['goods_commonid'] = $goods_commonid;
        $condition['goods_state'] = 1;
        $condition['goods_verify'] = 1;
        $field = 'goods_id,goods_name,store_id,goods_price,goods_spec,goods_storage,goods_image';

        $goods_list = Model('goods')->where($condition)->field($field)->select();
        foreach ($goods_list as $item => $value) {
            $spec = unserialize($value['goods_spec']);
            $spec_info = '';
            foreach ($spec as $s_item => $s_val) {
                $spec_info .= $s_val . ' ';
            }
            $goods_list[$item]['goods_spec'] = $spec_info;
            $goods_list[$item]['source_price'] = $value['goods_price'];
        }

        if (empty($goods_list)) {
            $data['result'] = false;
            $data['message'] = L('param_error');
            echo json_encode($data);
            die;
        }

        $data['result'] = true;
        $data['message'] = 'success';
        $data['data'] = $goods_list;
        echo json_encode($data);
        die;
    }

    public function check_groupbuy_goodsOp()
    {
        $start_time = strtotime($_GET['start_time']);
        $goods_id = $_GET['goods_id'];

        $model_groupbuy = Model('groupbuy');

        $data = array();
        $data['result'] = true;

        //检查商品是否已经参加同时段活动
        $condition = array();
        $condition['end_time'] = array('gt', $start_time);
        $condition['goods_id'] = $goods_id;
        $groupbuy_list = $model_groupbuy->getGroupbuyAvailableList($condition);
        if (!empty($groupbuy_list)) {
            $data['result'] = false;
            echo json_encode($data);
            die;
        }

        echo json_encode($data);
        die;
    }

    /**
     * 上传图片
     **/
    public function image_uploadOp()
    {
        if (!empty($_POST['old_groupbuy_image'])) {
            $this->_image_del($_POST['old_groupbuy_image']);
        }
        $this->_image_upload('groupbuy_image');
    }

    private function _image_upload($file)
    {
        $data = array();
        $data['result'] = true;
        if (!empty($_FILES[$file]['name'])) {
            $upload = new UploadFile();
            $uploaddir = ATTACH_PATH . DS . 'groupbuy' . DS . $_SESSION['store_id'] . DS;
            $upload->set('default_dir', $uploaddir);
            $upload->set('thumb_width', '480,296,168');
            $upload->set('thumb_height', '480,296,168');
            $upload->set('thumb_ext', '_max,_mid,_small');
            $upload->set('fprefix', $_SESSION['store_id']);
            $result = $upload->upfile($file);
            if ($result) {
                $data['file_name'] = $upload->file_name;
                $data['origin_file_name'] = $_FILES[$file]['name'];
                $data['file_url'] = gthumb($upload->file_name, 'mid');
            } else {
                $data['result'] = false;
                $data['message'] = $upload->error;
            }
        } else {
            $data['result'] = false;
        }
        echo json_encode($data);
        die;
    }

    /**
     * 图片删除
     */
    private function _image_del($image_name)
    {
        list($base_name, $ext) = explode(".", $image_name);
        $base_name = str_replace('/', '', $base_name);
        $base_name = str_replace('.', '', $base_name);
        list($store_id) = explode('_', $base_name);
        $image_path = BASE_UPLOAD_PATH . DS . ATTACH_GROUPBUY . DS . $store_id . DS;
        $image = $image_path . $base_name . '.' . $ext;
        $image_small = $image_path . $base_name . '_small.' . $ext;
        $image_mid = $image_path . $base_name . '_mid.' . $ext;
        $image_max = $image_path . $base_name . '_max.' . $ext;
        @unlink($image);
        @unlink($image_small);
        @unlink($image_mid);
        @unlink($image_max);
    }

    /**
     * 选择活动商品
     **/
    public function search_goodsOp()
    {
        $model_goods = Model('goods');
        $condition = array();
        $condition['store_id'] = $_SESSION['store_id'];
        $condition['goods_name'] = array('like', '%' . $_GET['goods_name'] . '%');
        $goods_list = $model_goods->getGeneralGoodsCommonList($condition, '*', 8);

        Tpl::output('goods_list', $goods_list);
        Tpl::output('show_page', $model_goods->showpage());
        Tpl::showpage('store_groupbuy.goods', 'null_layout');
    }

    /**
     * 添加虚拟抢购页面
     */
    public function groupbuy_add_vrOp()
    {
        $model_groupbuy_quota = Model('groupbuy_quota');

        if (checkPlatformStore()) {
            Tpl::output('isOwnShop', true);
        } else {
            $current_groupbuy_quota = $model_groupbuy_quota->getGroupbuyQuotaCurrent($_SESSION['store_id']);
            if (empty($current_groupbuy_quota)) {
                showMessage('当前没有可用套餐，请先购买套餐', urlShop('store_groupbuy', 'groupbuy_quota_add'), '', 'error');
            }
            Tpl::output('current_groupbuy_quota', $current_groupbuy_quota);
        }

        // 根据后台设置的审核期重新设置抢购开始时间
        Tpl::output('groupbuy_start_time', TIMESTAMP + intval(C('groupbuy_review_day')) * 86400);

        // 虚拟抢购分类
        // Tpl::output('groupbuy_vr_classes', Model('groupbuy')->getGroupbuyVrClasses());
        $model_vr_groupbuy_class = Model('vr_groupbuy_class');
        $classlist = $model_vr_groupbuy_class->getVrGroupbuyClassList(array('parent_class_id' => 0));
        Tpl::output('classlist', $classlist);

        // 虚拟区域分类
        // Tpl::output('groupbuy_vr_cities', Model('groupbuy')->getGroupbuyVrCities());
        $model_vr_groupbuy_area = Model('vr_groupbuy_area');
        $arealist = $model_vr_groupbuy_area->getVrGroupbuyAreaList(array('parent_area_id' => 0, 'hot_city' => 1), '', '100');
        Tpl::output('arealist', $arealist);

        self::profile_menu('groupbuy_add_vr');
        Tpl::showpage('store_groupbuy.add_vr');
    }

    public function ajax_vr_classOp()
    {
        $class_id = intval($_GET['class_id']);
        if (empty($class_id)) {
            exit('false');
        }

        $condition = array();
        $condition['parent_class_id'] = $class_id;

        $model_vr_groupbuy_class = Model('vr_groupbuy_class');
        $class_list = $model_vr_groupbuy_class->getVrGroupbuyClassList($condition);

        if (!empty($class_list)) {
            echo json_encode($class_list);
        } else {
            echo 'false';
        }

        exit;
    }

    public function ajax_vr_areaOp()
    {
        $area_id = intval($_GET['area_id']);
        if (empty($area_id)) {
            exit('false');
        }

        $condition = array();
        $condition['parent_area_id'] = $area_id;

        $model_vr_groupbuy_area = Model('vr_groupbuy_area');
        $area_list = $model_vr_groupbuy_area->getVrGroupbuyAreaList($condition);

        if (!empty($area_list)) {
            echo json_encode($area_list);
        } else {
            echo 'false';
        }

        exit;
    }

    /**
     * 选择活动虚拟商品
     */
    public function search_vr_goodsOp()
    {
        $model_goods = Model('goods');
        $condition = array();
        $condition['store_id'] = $_SESSION['store_id'];
        $condition['goods_name'] = array('like', '%' . $_GET['goods_name'] . '%');
        $goods_list = $model_goods->getVrGoodsCommonList($condition, '*', 8);

        Tpl::output('goods_list', $goods_list);
        Tpl::output('show_page', $model_goods->showpage());
        Tpl::showpage('store_groupbuy.goods', 'null_layout');
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string $menu_key 当前导航的menu_key
     * @param array  $array 附加菜单
     *
     * @return
     */
    private function profile_menu($menu_key = '')
    {
        $menu_array = array(
            1 => array('menu_key' => 'groupbuy_list', 'menu_name' => L('nc_member_path_group_list'), 'menu_url' => urlShop('store_groupbuy', 'groupbuy_list'))
        );
        switch ($menu_key) {
            case 'groupbuy_add':
                $menu_array[] = array('menu_key' => 'groupbuy_add', 'menu_name' => L('nc_member_path_new_group'), 'menu_url' => 'index.php?control=store_groupbuy&op=groupbuy_add');
                break;
            case 'groupbuy_add_vr':
                $menu_array[] = array('menu_key' => 'groupbuy_add_vr', 'menu_name' => '新增虚拟抢购', 'menu_url' => 'index.php?control=store_groupbuy&op=groupbuy_add_vr');
                break;
            case 'groupbuy_quota_add':
                $menu_array[] = array('menu_key' => 'groupbuy_quota_add', 'menu_name' => '购买套餐', 'menu_url' => urlShop('store_groupbuy', 'groupbuy_quota_add'));
                break;
            case 'groupbuy_edit':
                $menu_array[] = array('menu_key' => 'groupbuy_edit', 'menu_name' => L('nc_member_path_edit_group'), 'menu_url' => 'index.php?control=store_groupbuy');
                break;
            case 'cancel':
                $menu_array[] = array('menu_key' => 'groupbuy_cancel', 'menu_name' => L('nc_member_path_cancel_group'));
                break;
        }
        Tpl::output('member_menu', $menu_array);
        Tpl::output('menu_key', $menu_key);
    }
}
